﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using RiskMan.DataClass.Models;
using RiskMan.DataClass.Models.Level;
using RiskMan.DataClass.Models.NotBasModels;
using RiskMan.Views.Dialogs;
using TheControllerRisk.Settings;
using Brush = System.Drawing.Brush;


namespace RiskMan.Views.Level
{
    /// <summary>
    /// Логика взаимодействия для NewLevel.xaml
    /// </summary>
    public partial class NewLevel : Window
    {
        private DataClass.Models.Level.LevelItem lvItem;
        private DataClass.Data data;
        List<Trade> trades;

        public NewLevel(LevelItem item, DataClass.Data data, bool isedit)
        {
            InitializeComponent();
            lvItem = item;
            //this.lvItem = lvItem;
            this.data = data;
            trades = data.GetTradeList();



            cmbx_ClientCode.ItemsSource = trades.Select(a => a.ClientCode).ToList();
            for (int i = 0; i < cmbx_ClientCode.Items.Count; i++)
            {
                if (cmbx_ClientCode.Items[i].ToString() == lvItem.ClientCode)
                    cmbx_ClientCode.SelectedIndex = i;
            }
            cmbx_TypeDeal.ItemsSource = new List<string>() { cfg.Buy, cfg.Sell };
            cmbx_TypeLevel.ItemsSource = new List<string>()
            {
                cfg.HorizontalLevel,
                cfg.HorizontalLevelFalse,
                cfg.TrendLevel,
                cfg.TrendLevelFalse,
                cfg.DoubleLevel
            };
            cmbxInterval.ItemsSource = new List<string>()
            {
                cfg.min1,
                cfg.min2,
                cfg.min3,
                cfg.min4,
                cfg.min5,
                cfg.min6,
                cfg.min10,
                cfg.min15,
                cfg.min20,
                cfg.min30,
                cfg.hour1,
                cfg.hour2,
                cfg.hour4,
                cfg.day,
                cfg.week,
                cfg.month
            };
            cmbx_TypeDeal.SelectedIndex = 0;
            cmbxInterval.SelectedIndex = 0;
            txbxQuantity.Text = lvItem.Quantity.ToString();
            if (lvItem.SettingOrderOpenClose == null)
                lvItem.SettingOrderOpenClose = new SettingOrderOpenClosePoz();

            if (lvItem.NumberOfAttempt != 0)
                txbxNumberOfAttempt.Text = lvItem.NumberOfAttempt.ToString();
            txbx_Excess.Text = lvItem.Excess.ToString();
            txbxBreakeven.Text = lvItem.Breakeven.ToString();
            txbxBreakevenOtstup.Text = lvItem.Breakeven.ToString();

            cmbx_TypeLevel.SelectedIndex = 0;

            if (lvItem.Operation != null)
                cmbx_TypeDeal.SelectedValue = lvItem.Operation;
            if (lvItem.TypeLevel != null)
                cmbx_TypeLevel.SelectedValue = lvItem.TypeLevel;


            if (lvItem.trendItem == null)
                lvItem.trendItem = new DataClass.Models.Level.TrendItem();
            if (lvItem.trendItem.Interval != null)
                cmbxInterval.SelectedValue = lvItem.trendItem.Interval;
            txbxNameLevel.Text = lvItem.trendItem.NameTrend;

            txbxPriceLevelHorizontal.Text = lvItem.trendItem.HorizontalLevel.ToString();

            TxbxDateFirstCandle.Text = lvItem.trendItem.DateTimeFirstCandle.ToString();
            if (lvItem.trendItem.DateTimeFirstCandle.Year == 1)
                TxbxDateFirstCandle.Text = DateTime.Now.ToString();
            txbxPriceFirstCandle.Text = lvItem.trendItem.PriceFirstCandle.ToString();

            txbxDateSecondCandle.Text = lvItem.trendItem.DateTimeSecondCandle.ToString();
            if (lvItem.trendItem.DateTimeSecondCandle.Year == 1)
                txbxDateSecondCandle.Text = DateTime.Now.ToString();
            txbxPriceSecondCandle.Text = lvItem.trendItem.PriceSecondCandle.ToString();

            txbxMinProkol.Text = lvItem.trendItem.MinProkol.ToString();
            txbxMaxProkol.Text = lvItem.trendItem.MaxProkol.ToString();
            txbxTimeFalseProboi.Text = lvItem.trendItem.TimeFalseProboi.ToString();

            #region Seccode

            cmbx_Instrument.ItemsSource = data.GetSeccodeList();
            for (int i = 0; i < cmbx_Instrument.Items.Count; i++)
            {
                if (cmbx_Instrument.Items[i].ToString() == lvItem.Instrument)
                    cmbx_Instrument.SelectedIndex = i;
            }

            #endregion

            //Двойной уровень
            txbxDownLevel.Text = lvItem.trendItem.DownLevel.ToString();
            txbxUpLevel.Text = lvItem.trendItem.UpLevel.ToString();

            //параметры на заявки на открытие
            if (Properties.Settings.Default.adapter == cfg.adapterQuik)
                cmbxTypeOrderOpen.ItemsSource = new List<string>() { cfg.openOrderLimit, cfg.openOrderMarket };
            else
                cmbxTypeOrderOpen.ItemsSource = new List<string>() { cfg.openOrderLimit };

            cmbxTypeOrderOpen.SelectedIndex = 0;
            cmbxKillOrderOpen.ItemsSource = new List<string>()
            {
                cfg.Unknown,
                cfg.KillofTime,
                cfg.KillOfDictance,
                cfg.KillOfTimeOrDistance
            };
            cmbxKillOrderOpen.SelectedIndex = 0;
            if (lvItem.SettingOrderOpenClose.TypeOrderOpen != null)
                cmbxTypeOrderOpen.SelectedValue = lvItem.SettingOrderOpenClose.TypeOrderOpen;
            if (lvItem.SettingOrderOpenClose.KillOrderOpen != null)
                cmbxKillOrderOpen.SelectedValue = lvItem.SettingOrderOpenClose.KillOrderOpen;

            txbxOtstupForOpenOrder.Text = lvItem.SettingOrderOpenClose.OtstupForOpenOrder.ToString();
            txbxTimeWiatOpenPoz.Text = lvItem.SettingOrderOpenClose.TimeWiatOpenPoz.ToString();
            txbxSpredForKillOrderOpen.Text = lvItem.SettingOrderOpenClose.SpredForKillOrderOpen.ToString();


            //Параметры стоп-заявки
            cmbxTypeofPricing.ItemsSource = new List<string>() { cfg.TypeCloseOrderAuto, cfg.TypeCloseOrderManual };
            cmbxTypeStop.ItemsSource = new List<string>() { cfg.LinkedOrder };
            cmbxTypeofPricing.SelectedIndex = 0;
            cmbxTypeStop.SelectedIndex = 0;
            if (lvItem.SettingOrderOpenClose.TypePricing != null)
                cmbxTypeofPricing.SelectedValue = lvItem.SettingOrderOpenClose.TypePricing;
            if (lvItem.SettingOrderOpenClose.TypeStop != null)
                cmbxTypeStop.SelectedValue = lvItem.SettingOrderOpenClose.TypeStop;

            txbxStopLimitOtstup.Text = lvItem.SettingOrderOpenClose.StopLimitOtstup.ToString();
            txbxStopLimitSpred.Text = lvItem.SettingOrderOpenClose.StopLimitSpred.ToString();
            txbxLimitOrderProfit.Text = lvItem.SettingOrderOpenClose.Profit.ToString();

            ChbxUseDeposit.IsChecked = lvItem.QuantityFromDeposit;
            ChbxUseTimeOpenPoz.IsChecked = lvItem.UseTimeOpen;
            TxbxTimeStartOpenPoz.Text = lvItem.TimeStartOpenPoz.TimeOfDay.ToString();
            TxbxTimeEndOpenPoz.Text = lvItem.TimeEndOpenPoz.TimeOfDay.ToString();
            ChbxUseTimeClosePoz.IsChecked = lvItem.UseTimeClose;
            TxbxTimeClosePoz.Text = lvItem.TimeClosePoz.TimeOfDay.ToString();

            if (ChbxUseTimeOpenPoz.IsChecked == false)
            {
                TxbxTimeStartOpenPoz.IsEnabled = false;
                TxbxTimeEndOpenPoz.IsEnabled = false;
                LblTimeStartOpenPoz.Foreground = Brushes.DarkGray;
                LblTimeEndOpenPoz.Foreground = Brushes.DarkGray;
            }
            if (ChbxUseTimeClosePoz.IsChecked == false)
            {
                TxbxTimeClosePoz.IsEnabled = false;
                LblTimeClosePoz.Foreground = Brushes.DarkGray;
            }
        }

        private void Button_Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void cmbx_TypeLevelEnabled()
        {


            if (cmbx_TypeLevel.SelectedValue.ToString() == cfg.HorizontalLevel || cmbx_TypeLevel.SelectedValue.ToString() == cfg.HorizontalLevelFalse)
            {
                txbxPriceLevelHorizontal.IsEnabled = true;

                txbxPriceSecondCandle.IsEnabled = false;
                txbxPriceFirstCandle.IsEnabled = false;
                TxbxDateFirstCandle.IsEnabled = false;
                txbxDateSecondCandle.IsEnabled = false;
                cmbxInterval.IsEnabled = false;

                txbxDownLevel.IsEnabled = false;
                txbxUpLevel.IsEnabled = false;

                if (cmbx_TypeLevel.SelectedValue.ToString() == cfg.HorizontalLevel)
                {
                    txbx_Excess.IsEnabled = true;
                    txbxMinProkol.IsEnabled = false;
                    txbxMaxProkol.IsEnabled = false;
                    txbxTimeFalseProboi.IsEnabled = false;
                }
                else
                {
                    txbx_Excess.IsEnabled = false;
                    txbxMinProkol.IsEnabled = true;
                    txbxMaxProkol.IsEnabled = true;
                    txbxTimeFalseProboi.IsEnabled = true;
                }
            }
            if (cmbx_TypeLevel.SelectedValue.ToString() == cfg.TrendLevel || cmbx_TypeLevel.SelectedValue.ToString() == cfg.TrendLevelFalse)
            {
                txbxPriceLevelHorizontal.IsEnabled = false;

                txbxPriceSecondCandle.IsEnabled = true;
                txbxPriceFirstCandle.IsEnabled = true;
                TxbxDateFirstCandle.IsEnabled = true;
                txbxDateSecondCandle.IsEnabled = true;
                cmbxInterval.IsEnabled = true;

                txbxDownLevel.IsEnabled = false;
                txbxUpLevel.IsEnabled = false;

                if (cmbx_TypeLevel.SelectedValue.ToString() == cfg.TrendLevel)
                {
                    txbx_Excess.IsEnabled = true;
                    txbxMinProkol.IsEnabled = false;
                    txbxMaxProkol.IsEnabled = false;
                    txbxTimeFalseProboi.IsEnabled = false;
                }
                else
                {
                    txbx_Excess.IsEnabled = false;
                    txbxMinProkol.IsEnabled = true;
                    txbxMaxProkol.IsEnabled = true;
                    txbxTimeFalseProboi.IsEnabled = true;
                }
            }

            if (cmbx_TypeLevel.SelectedValue.ToString() == cfg.DoubleLevel)
            {
                txbxPriceLevelHorizontal.IsEnabled = false;

                txbxPriceSecondCandle.IsEnabled = false;
                txbxPriceFirstCandle.IsEnabled = false;
                TxbxDateFirstCandle.IsEnabled = false;
                txbxDateSecondCandle.IsEnabled = false;
                cmbxInterval.IsEnabled = false;

                txbx_Excess.IsEnabled = false;
                txbxMinProkol.IsEnabled = false;
                txbxMaxProkol.IsEnabled = false;
                txbxTimeFalseProboi.IsEnabled = false;

                txbxDownLevel.IsEnabled = true;
                txbxUpLevel.IsEnabled = true;
            }
        }

        private void Button_Accept_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                lvItem.TypeLevel = cmbx_TypeLevel.Text;
                if (lvItem.TypeLevel == cfg.TrendLevel || lvItem.TypeLevel == cfg.TrendLevelFalse)
                {

                    try
                    {
                        if (Convert.ToDateTime(TxbxDateFirstCandle.Text).Date.Year == 2014 &&
                                        Convert.ToDateTime(txbxDateSecondCandle.Text).Date.Year == 2014)
                        {
                            TrendLevel trLevel = new TrendLevel();
                            double tmpStepPrice = 0;
                            lvItem.trendItem.DateTimeFirstCandle = Convert.ToDateTime(TxbxDateFirstCandle.Text);
                            lvItem.trendItem.DateTimeSecondCandle = Convert.ToDateTime(txbxDateSecondCandle.Text);
                            lvItem.trendItem.PriceFirstCandle = Convert.ToDouble(txbxPriceFirstCandle.Text);
                            lvItem.trendItem.PriceSecondCandle = Convert.ToDouble(txbxPriceSecondCandle.Text);
                            lvItem.trendItem.Interval = cmbxInterval.Text;
                            lvItem.trendItem.TrendCandleCount = trLevel.GetCountCandleBetweenDate(lvItem, ref tmpStepPrice);
                            lvItem.trendItem.StepTrendCandle = tmpStepPrice;
                        }

                    }
                    catch
                    {
                        new DialogOkCancel("Проверьте правильность записи даты и времени для тренда", "Ошибка добавления");
                        return;

                    }

                }

                if (cmbx_ClientCode.SelectedIndex >= 0)
                {
                    lvItem.ClientCode = cmbx_ClientCode.SelectedValue.ToString();
                    List<Trade> trades = data.GetTradeList();

                    for (int i = 0; i < trades.Count; i++)
                        if (trades[i].ClientCode == lvItem.ClientCode)
                            lvItem.Account = trades[i].Account;
                }
                else
                {
                    new DialogOkCancel("Выберите код клиента(счет)!", "Ошибка добавления");
                    return;
                }

                if (cmbx_TypeDeal.SelectedIndex >= 0)
                    lvItem.Operation = cmbx_TypeDeal.SelectedValue.ToString();
                else
                {
                    new DialogOkCancel("Выберите вид операции!", "Ошибка добавления");
                    return;
                }

                if (cmbx_Instrument.SelectedIndex >= 0)
                    if (cmbx_Instrument.SelectedValue.ToString() != "Не выбран")
                        lvItem.Instrument = cmbx_Instrument.SelectedValue.ToString();
                    else
                    {
                        new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                        return;
                    }
                else
                {
                    new DialogOkCancel("Выберите торгуемый инструмент!", "Ошибка добавления");
                    return;
                }

                lvItem.Quantity = Convert.ToInt32(txbxQuantity.Text);
                lvItem.NumberOfAttempt = Convert.ToInt32(txbxNumberOfAttempt.Text);
                lvItem.Breakeven = Convert.ToDouble(txbxBreakeven.Text);
                lvItem.BreakevenOtstup = Convert.ToDouble(txbxBreakevenOtstup.Text);


                lvItem.trendItem.NameTrend = txbxNameLevel.Text;
                lvItem.trendItem.HorizontalLevel = Convert.ToDouble(txbxPriceLevelHorizontal.Text);


                lvItem.Excess = Convert.ToDouble(txbx_Excess.Text);
                lvItem.trendItem.MinProkol = Convert.ToDouble(txbxMinProkol.Text);
                lvItem.trendItem.MaxProkol = Convert.ToDouble(txbxMaxProkol.Text);
                lvItem.trendItem.TimeFalseProboi = Convert.ToInt32(txbxTimeFalseProboi.Text);

                lvItem.SettingOrderOpenClose.TypeOrderOpen = cmbxTypeOrderOpen.Text;
                lvItem.SettingOrderOpenClose.KillOrderOpen = cmbxKillOrderOpen.Text;
                lvItem.SettingOrderOpenClose.OtstupForOpenOrder = Convert.ToDouble(txbxOtstupForOpenOrder.Text);
                lvItem.SettingOrderOpenClose.TimeWiatOpenPoz = Convert.ToInt32(txbxTimeWiatOpenPoz.Text);
                lvItem.SettingOrderOpenClose.SpredForKillOrderOpen = Convert.ToDouble(txbxSpredForKillOrderOpen.Text);

                lvItem.SettingOrderOpenClose.TypePricing = cmbxTypeofPricing.Text;
                lvItem.SettingOrderOpenClose.TypeStop = cmbxTypeStop.Text;
                lvItem.SettingOrderOpenClose.StopLimitOtstup = Convert.ToDouble(txbxStopLimitOtstup.Text);
                lvItem.SettingOrderOpenClose.StopLimitSpred = Convert.ToDouble(txbxStopLimitSpred.Text);
                lvItem.SettingOrderOpenClose.Profit = Convert.ToDouble(txbxLimitOrderProfit.Text);

                //Двойной уровень
                if (lvItem.TypeLevel == cfg.DoubleLevel)
                {
                    lvItem.trendItem.UpLevel = Convert.ToDouble(txbxUpLevel.Text);
                    lvItem.trendItem.DownLevel = Convert.ToDouble(txbxDownLevel.Text);
                    if (lvItem.trendItem.DownLevel <= 0 || lvItem.trendItem.UpLevel <= 0)
                    {
                        new DialogOkCancel("Параметры трнеда (верхний и нижний уровень) не могут равняться нулю!", "Ошибка добавления");
                        return;
                    }
                }



                if (lvItem.NumberOfAttempt <= 0 ||
                    lvItem.Quantity <= 0 || lvItem.SettingOrderOpenClose.Profit <= 0 || lvItem.SettingOrderOpenClose.StopLimitOtstup <= 0)
                {
                    new DialogOkCancel("Параметр количесвто контрактов/лотов, количество попыток, профит или отступ (ЦА) не может равняться нулю!", "Ошибка добавления");
                    return;
                }

                if (cmbxKillOrderOpen.Text != cfg.Unknown)
                {
                    if (cmbxKillOrderOpen.Text == cfg.KillofTime)
                        if (lvItem.SettingOrderOpenClose.TimeWiatOpenPoz == 0)
                            new DialogOkCancel("Время ожидания не может равняться нулю!", "Ошибка добавления");

                    if (cmbxKillOrderOpen.Text == cfg.KillOfDictance)
                        if (lvItem.SettingOrderOpenClose.SpredForKillOrderOpen == 0)
                            new DialogOkCancel("Отклонение цнеы не может равняться нулю!", "Ошибка добавления");

                    if (cmbxKillOrderOpen.Text == cfg.KillOfTimeOrDistance)
                        if (lvItem.SettingOrderOpenClose.TimeWiatOpenPoz == 0 || lvItem.SettingOrderOpenClose.SpredForKillOrderOpen == 0)
                            new DialogOkCancel("Время ожидания и отлонение цены не может равняться нулю!", "Ошибка добавления");
                }

                if (lvItem.TypeLevel == cfg.HorizontalLevel || lvItem.TypeLevel == cfg.HorizontalLevelFalse)
                {
                    if (lvItem.trendItem.HorizontalLevel <= 0)
                    {
                        new DialogOkCancel("Параметр горизонтального уровня не может равняться нулю!", "Ошибка добавления");
                        return;
                    }
                }
                if (lvItem.TypeLevel == cfg.TrendLevel || lvItem.TypeLevel == cfg.TrendLevelFalse)
                {
                    if (lvItem.trendItem.PriceFirstCandle <= 0 || lvItem.trendItem.PriceSecondCandle <= 0)
                    {
                        new DialogOkCancel("Параметры трнеда не могут равняться нулю!", "Ошибка добавления");
                        return;
                    }
                    //необходимо сделать провеку по датам!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                }
                //data.LevelItems.Add(lvItem);

                lvItem.QuantityFromDeposit = Convert.ToBoolean(ChbxUseDeposit.IsChecked);
                lvItem.UseTimeOpen = Convert.ToBoolean(ChbxUseTimeOpenPoz.IsChecked);

                if (lvItem.UseTimeOpen)
                {
                    if ((TxbxTimeEndOpenPoz.Text == "00:00:00") || (Convert.ToDateTime(TxbxTimeStartOpenPoz.Text) >= Convert.ToDateTime(TxbxTimeEndOpenPoz.Text)))
                    {
                        new DialogOkCancel("Используется время открытия позици. Время ококнчания не может быть равно или меньше времени начала!", "Ошибка добавления");
                        return;
                    }
                }
                lvItem.TimeStartOpenPoz = Convert.ToDateTime(TxbxTimeStartOpenPoz.Text);
                lvItem.TimeEndOpenPoz = Convert.ToDateTime(TxbxTimeEndOpenPoz.Text);


                lvItem.UseTimeClose = Convert.ToBoolean(ChbxUseTimeClosePoz.IsChecked);
                if (lvItem.UseTimeClose)
                {
                    if (TxbxTimeClosePoz.Text == "00:00:00")
                    {
                        new DialogOkCancel("Используется закрытие позиций. Время закрытия не может быть равно 00:000:00!", "Ошибка добавления");
                        return;
                    }
                }
                lvItem.TimeClosePoz = Convert.ToDateTime(TxbxTimeClosePoz.Text);

                if (lvItem.TradeList == null)
                    lvItem.TradeList = new ObservableCollection<TradesOpen>();

                this.Close();
            }
            catch
            { }


        }

        private void cmbx_TypeLevel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            cmbx_TypeLevelEnabled();
        }

        private void txbxPriceFirstCandle_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;

            if ((e.Text.IndexOf('.') == 0 || e.Text.IndexOf(',') == 0) && ((TextBox)sender).Text.IndexOf('.') == -1 && ((TextBox)sender).Text.IndexOf(',') == -1)
                e.Handled = false;
        }

        private void txbxPriceFirstCandle_GotFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text != "")
                if (Convert.ToDouble(((TextBox)sender).Text) == 0)
                {
                    ((TextBox)sender).Text = "";
                }
        }

        private void txbxNumberOfAttempt_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            if (!Char.IsDigit(e.Text, 0))
                e.Handled = true;
        }

        private void TxbxLostFocus(object sender, RoutedEventArgs e)
        {
            if (((TextBox)sender).Text == "")
                ((TextBox)sender).Text = 0.ToString();
        }

        private void ChbxUseTimeOpenPoz_Checked(object sender, RoutedEventArgs e)
        {
            TxbxTimeStartOpenPoz.IsEnabled = true;
            TxbxTimeEndOpenPoz.IsEnabled = true;
            LblTimeStartOpenPoz.Foreground = Brushes.White;
            LblTimeEndOpenPoz.Foreground = Brushes.White;
        }

        private void ChbxUseTimeClosePoz_Checked(object sender, RoutedEventArgs e)
        {
            TxbxTimeClosePoz.IsEnabled = true;
            LblTimeClosePoz.Foreground = Brushes.White;
        }

        private void ChbxUseTimeOpenPoz_OnUnchecked(object sender, RoutedEventArgs e)
        {
            TxbxTimeStartOpenPoz.IsEnabled = false;
            TxbxTimeEndOpenPoz.IsEnabled = false;

            LblTimeStartOpenPoz.Foreground = Brushes.DarkGray;
            LblTimeEndOpenPoz.Foreground = Brushes.DarkGray;
        }

        private void ChbxUseTimeClosePoz_OnUnchecked(object sender, RoutedEventArgs e)
        {
            TxbxTimeClosePoz.IsEnabled = false;
            LblTimeClosePoz.Foreground = Brushes.DarkGray;

        }
    }
}
